from django.shortcuts import render
from django.views import View
from django import http
from django.core.cache import cache
from apps.areas.models import Areas
import logging
logger = logging.getLogger('django')
# Create your views here.


class ProvinceAreasView(View):
    def get(self, request):
        province_list = cache.get('province_list')
        if province_list:
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})
        try:
            province_models_list = Areas.objects.filter(parent__isnull = True)
            province_list = []
            for province_model in province_models_list:
                province_list.append({'id': province_model.id,
                                      'name': province_model.name})
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '省份数据错误'})
        cache.set('province_list', province_list, 3600)
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})


class SubAreasView(View):
    def get(self, request, pk):
        sub_data = cache.get('sub_data_%s' % pk)
        if sub_data:
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})
        try:
            province_area = Areas.objects.get(id=pk)
            sub_areas_list = province_area.subs.all()
            subs = []
            for sub_area in sub_areas_list:
                subs.append({
                    'id': sub_area.id,
                    'name': sub_area.name
                })
            sub_data = {
                'id': province_area.id,
                'name': province_area.name,
                'subs': subs
            }
            cache.set('sub_data_%s' % pk, sub_data, 3600)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '市区数据错误'})
        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})

